type ToggleAll = (val: boolean) => void

/**
 * 半选
 * @param tableList table数据
 * @param selected 选中数据
 * @param toggleAll 切换全选
 * @returns
 */
export function useTableCheck<T extends any[]>(
  tableList: RefSource<T>,
  selected: RefSource<T>,
  toggleAll: ToggleAll
) {
  const checkAll = ref(false)
  const list = getSource(tableList)
  const select = getSource(selected)

  const indeterminate = computed(() => {
    const selectLength = select.value.length
    const tableLength = list.value.length
    return !!tableLength && !!selectLength && selectLength < tableLength
  })

  watch(
    [() => select.value.length, () => list.value.length],
    ([selectLength, tableLength]) => {
      checkAll.value =
        !!selectLength && !!tableLength && selectLength === tableLength
    }
  )

  watch(checkAll, checkAll => {
    const i = indeterminate.value
    if ((!checkAll && !i) || checkAll) toggleAll(checkAll)
  })

  watch(list, () => toggleAll(false))
  return { indeterminate, checkAll }
}
